/**
 * Created by chengming on 18/5/27.
 * version 1.0
 */
const BaseJsonAdapter = require('../base/BaseJsonAdapter');
const iconv = require("iconv-lite");
const vm = require('vm');
const request = require('request-promise');
const logger = require('../../conf/logger');
const querystring = require("querystring")
const cheerio = require('cheerio');
const urlTool = require('url');

/**
 * 北京互金网
 * @type {module.Bjp2p}
 */
module.exports = class TencentCaiJing extends BaseJsonAdapter{

    /*async doRequest(){
        var form = {
            page: 1,
            num: 10,
            type: 21
        }

        var formData = querystring.stringify(form);
        var contentLength = formData.length;

        var options = {
            headers:{
                'Content-Length': contentLength,
                'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8'
            },
            // uri:'http://www.bjp2p.com.cn/supervise/queryNews4List',
            uri:this.requestUrl,
            body:formData,
            method:"POSt",
            encoding:null
        }
        let body = await request(options)
        return body;
    }*/


    async reqJson(){
		const body = await this.doRequest();
        let decodeBody = iconv.decode(body, this.encoding).toString();
        let obj = JSON.parse(decodeBody);
        let html = obj.data.article_info;

        let data = this.parseHtml(html,"li a")

        console.log("-----decodeBody: " + decodeBody)
		return data;
	}

    parseHtml(html, linkRule){
        //将解析后的内容加载进解析器
        let $ = cheerio.load(html);

        let contents = [];
        let that = this;
        let rangeText = '';
        $(linkRule).each( function() {

            let title = $(this).text().trim();
            let href = '';
            if($(this).is('a') && $(this).attr('href')){
                href = urlTool.resolve(that.requestUrl, $(this).attr('href'));
            }

            if(title.length != 0 || href.length != 0){
                contents.push({
                    title:title,
                    href:href
                });
                rangeText +=title+href;
            }
        });

        return {
            rangeText: rangeText,
            contents: contents
        };
    }
}
